package com.yx.cloud.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.DisplayMetrics;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

public class BitmapUtils {
    /**
     * 根据路径获取图片返回
     *
     * @param context
     * @param path
     * @return
     */
    public static Bitmap compressImage(Context context, String path) {
        InputStream compressImageStream = null;
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(path);
            BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(fileInputStream, null, options);
            DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
            int heightPixels = 400;
            int widthPixels = 400;
            int outHeight = options.outHeight;
            int outWidth = options.outWidth;
            int a = (int) Math.ceil((outHeight / (float) heightPixels));
            int b = (int) Math.ceil(outWidth / (float) widthPixels);
            //比例计算,一般是图片比较大的情况下进行压缩
            int max = Math.max(a, b);
            if (max > 1) {
                options.inSampleSize = max;
            }
            //解析到内存中去
            options.inJustDecodeBounds = false;
            compressImageStream = new FileInputStream(path);
            Bitmap bitmap = BitmapFactory.decodeStream(compressImageStream, null, options);
            return bitmap;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (compressImageStream != null) {
                    compressImageStream.close();
                }
                if (fileInputStream != null) {
                    fileInputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;

    }
}
